package handler

import (
	"encoding/json"
	"sept21-homework/cache"
	"sept21-homework/model"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")

	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	news := model.New{
		Title:   title,
		Content: content,
	}
	err := model.DB.Create(&news).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	//----------事务----------

	tx := model.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "发布失败",
			})
			return
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	redis_key := "new_add_" + strconv.Itoa(int(news.ID))
	var new model.New
	model.DB.Where("id=?", news.ID).First(&new)
	jsonData, _ := json.Marshal(new)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	err = tx.Commit().Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
		"data": news,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var news []model.New

	var total int64
	model.DB.Model(&news).Count(&total)

	redis_key := "new_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&news).Debug()
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表获取成功",
		"data":  news,
		"total": total,
	})
	return
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var news model.New

	redis_key := "new_select_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).First(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "搜索成功",
		"data": news,
	})
	return
}
